<!DOCTYPE html>
<html>
<head>
    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?a7c05ce530152d9866930ef4850ee566"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    
    
    
    <title>Mybatis快速入门七(二级缓存) | 神奇的鸭鸭の码农库 | 新知识要不断的总结记录成笔记，要多写，多画，能够清晰透彻的将知识讲给别人听，才是达到理解的层次。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#765959">
    
    
    <meta name="keywords" content="SSM">
    <meta name="description" content="Mybatis缓存本文学习自：《深入理解mybatis原理》 MyBatis的二级缓存的设计原理 MyBatis将数据缓存设计成两级结构，分为一级缓存、二级缓存： 一级缓存是Session会话级别的缓存，位于表示一次数据库会话的SqlSession对象之中，又被称之为本地缓存。一级缓存是MyBatis内部实现的一个特性，用户不能配置，默认情况下自动支持的缓存，用户没有定制它的权利（不过这也不是绝对">
<meta name="keywords" content="SSM">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis快速入门七(二级缓存)">
<meta property="og:url" content="http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/index.html">
<meta property="og:site_name" content="神奇的鸭鸭の码农库">
<meta property="og:description" content="Mybatis缓存本文学习自：《深入理解mybatis原理》 MyBatis的二级缓存的设计原理 MyBatis将数据缓存设计成两级结构，分为一级缓存、二级缓存： 一级缓存是Session会话级别的缓存，位于表示一次数据库会话的SqlSession对象之中，又被称之为本地缓存。一级缓存是MyBatis内部实现的一个特性，用户不能配置，默认情况下自动支持的缓存，用户没有定制它的权利（不过这也不是绝对">
<meta property="og:image" content="http://om6odecqr.bkt.clouddn.com/mybatis%E7%BC%93%E5%AD%98%E6%9C%BA%E5%88%B6">
<meta property="og:image" content="http://om6odecqr.bkt.clouddn.com/mybatis%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98">
<meta property="og:image" content="http://om6odecqr.bkt.clouddn.com/%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98cache1">
<meta property="og:image" content="http://om6odecqr.bkt.clouddn.com/%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98cache2">
<meta property="og:image" content="http://om6odecqr.bkt.clouddn.com/%E5%88%86%E5%B8%83%E5%BC%8F%E7%BC%93%E5%AD%98.png">
<meta property="og:updated_time" content="2017-12-05T10:18:11.284Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Mybatis快速入门七(二级缓存)">
<meta name="twitter:description" content="Mybatis缓存本文学习自：《深入理解mybatis原理》 MyBatis的二级缓存的设计原理 MyBatis将数据缓存设计成两级结构，分为一级缓存、二级缓存： 一级缓存是Session会话级别的缓存，位于表示一次数据库会话的SqlSession对象之中，又被称之为本地缓存。一级缓存是MyBatis内部实现的一个特性，用户不能配置，默认情况下自动支持的缓存，用户没有定制它的权利（不过这也不是绝对">
<meta name="twitter:image" content="http://om6odecqr.bkt.clouddn.com/mybatis%E7%BC%93%E5%AD%98%E6%9C%BA%E5%88%B6">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">神奇的鸭鸭</h5>
          <a href="mailto:702038338@qq.com" title="702038338@qq.com" class="mail">702038338@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/magic_duck" target="_blank" >
                <i class="icon icon-lg icon-gg-circle"></i>
                码云
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.zhihu.com/people/shen-qi-de-ya-ya" target="_blank" >
                <i class="icon icon-lg icon-twitter"></i>
                知乎
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">Mybatis快速入门七(二级缓存)</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">Mybatis快速入门七(二级缓存)</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-08-15T12:13:00.000Z" itemprop="datePublished" class="page-time">
  2017-08-15
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Mybatis缓存"><span class="post-toc-number">1.</span> <span class="post-toc-text">Mybatis缓存</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#二级缓存工作机制"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">二级缓存工作机制</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#测试代码"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">测试代码</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#禁用-刷新-二级缓存"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">禁用/刷新 二级缓存</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#MyBatis二级缓存的划分"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">MyBatis二级缓存的划分</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#一级缓存和二级缓存的使用顺序"><span class="post-toc-number">1.5.</span> <span class="post-toc-text">一级缓存和二级缓存的使用顺序</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#整合第三方二级缓存-Ehcache"><span class="post-toc-number">1.6.</span> <span class="post-toc-text">整合第三方二级缓存(Ehcache)</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#整合思路"><span class="post-toc-number">1.6.1.</span> <span class="post-toc-text">整合思路</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#应用场景和局限性"><span class="post-toc-number">1.6.2.</span> <span class="post-toc-text">应用场景和局限性</span></a></li></ol></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-Mybatis_primary_07"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">Mybatis快速入门七(二级缓存)</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年08月15日 20:13" datetime="2017-08-15T12:13:00.000Z"  itemprop="datePublished">2017-08-15</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h2 id="Mybatis缓存"><a href="#Mybatis缓存" class="headerlink" title="Mybatis缓存"></a>Mybatis缓存</h2><p>本文学习自：<a href="http://blog.csdn.net/luanlouis/article/details/41408341" target="_blank" rel="external">《深入理解mybatis原理》 MyBatis的二级缓存的设计原理</a></p>
<p>MyBatis将数据缓存设计成两级结构，分为一级缓存、二级缓存：</p>
<p>一级缓存是Session会话级别的缓存，位于表示一次数据库会话的SqlSession对象之中，又被称之为本地缓存。一级缓存是MyBatis内部实现的一个特性，用户不能配置，默认情况下自动支持的缓存，用户没有定制它的权利（不过这也不是绝对的，可以通过开发插件对它进行修改）；<br><a href="http://magic_duck.oschina.io/2017/08/15/Mybatis快速入门六(一级缓存">Mybatis快速入门六(一级缓存)</a>/)</p>
<p>二级缓存是Application应用级别的缓存，它的是生命周期很长，跟Application的声明周期一样，也就是说它的作用范围是整个Application应用。</p>
<p><strong>MyBatis中一级缓存和二级缓存的组织如下图所示：</strong></p>
<p><img src="http://om6odecqr.bkt.clouddn.com/mybatis%E7%BC%93%E5%AD%98%E6%9C%BA%E5%88%B6" alt="mybatis缓存机制"></p>
<h3 id="二级缓存工作机制"><a href="#二级缓存工作机制" class="headerlink" title="二级缓存工作机制"></a>二级缓存工作机制</h3><p>一级缓存是Session会话级别的，一般而言，一个SqlSession对象会使用一个Executor对象来完成会话操作，Executor对象会维护一个Cache缓存，以提高查询性能。</p>
<p>MyBatis的二级缓存机制的关键就是对这个Executor对象做文章，如果用户配置了<strong>“cahceEnable=true”</strong>，那么MyBatis在为SqlSession对象创建Executor对象时，会对Executor对象加上一个装饰者：CachingExecutor，这时候SqlSession使用CachingExecutor对象来完成操作请求。CachingExecutor对于查询请求，会先判断该查询请求在Application级别的二级缓存中是否有缓存结果，如果有查询结果，则直接返回缓存结果。如果缓存中没有，再交给真正的Executor对象来完成查询操作，之后CachingExecutor会将真正的Executor返回的查询结果放置到缓存中，然后再返回给用户。<br><img src="http://om6odecqr.bkt.clouddn.com/mybatis%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98" alt="mybatis二级缓存"><br>CachingExecutor是Executor的装饰者，以增强Executor的功能(增加了二级缓存的功能)，使其具有缓存查询的功能，这里用到了设计模式中的装饰设计模式。</p>
<p>Mybatis的二级缓存设计的比较灵活，你可以使用MyBatis自己定义的二级缓存实现<strong>(不推荐，不能实现分布式缓存)</strong>，也可以通过实现比如rg.apache.ibatis.cache.Cache接口自定义缓存<strong>(不推荐)</strong>，或者使用第三方缓存库，如ehcache、memcache、redis等<strong>(推荐，专业二级缓存厂商)</strong>。</p>
<h3 id="测试代码"><a href="#测试代码" class="headerlink" title="测试代码"></a>测试代码</h3><p>通过测试代码你可以看到：</p>
<p>1、第一次调用mapper下的SQL去查询用户信息。查询到的信息会存到该mapper对应的二级缓存区域内。</p>
<p>2、第二次调用相同namespace下的mapper映射文件中相同的SQL去查询用户信息。会去对应的二级缓存内取结果。</p>
<p>3、 如果调用相同namespace下的mapper映射文件中的增删改SQL，并执行了commit操作。此时会清空该namespace下的二级缓存。</p>
<p><strong>在核心配置文件中加入以下内容（开启二级缓存总开关）：</strong><br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 开启二级缓存总开关 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">setting</span> <span class="attr">name</span>=<span class="string">"cacheEnabled"</span> <span class="attr">value</span>=<span class="string">"true"</span>/&gt;</span></div></pre></td></tr></table></figure></p>
<p><strong>在映射文件中加入以下内容，开启二级缓存：</strong><br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 开启二级缓存，默认使用了PerpetualCache（Mybatis提供） --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">cache</span>&gt;</span><span class="tag">&lt;/<span class="name">cache</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p><strong>实现序列化，由于二级缓存的数据不一定时存储到内存中，它的存储介质多种多样，所以要给缓存的对象执行序列化，如果该类存在父类，父类也需实现序列化：</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> id;</div><div class="line">    <span class="keyword">private</span> String username;<span class="comment">// 用户姓名</span></div><div class="line">    <span class="keyword">private</span> String sex;<span class="comment">// 性别</span></div><div class="line">    <span class="keyword">private</span> Date birthday;<span class="comment">// 生日</span></div><div class="line">    <span class="keyword">private</span> String address;<span class="comment">// 地址</span></div><div class="line">    <span class="comment">// 一个用户持有多个订单</span></div><div class="line">    <span class="keyword">private</span> List&lt;Orders&gt; ordersList;</div></pre></td></tr></table></figure></p>
<p><strong>测试代码：</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 测试1：</span></div><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testTwoLevelCache</span><span class="params">()</span> </span>&#123;</div><div class="line">    SqlSession session1 = sqlSessionFactory.openSession();</div><div class="line">    SqlSession session2 = sqlSessionFactory.openSession();</div><div class="line">    </div><div class="line">    UserMapper mapper1 = session1.getMapper(UserMapper.class);</div><div class="line">    UserMapper mapper2 = session2.getMapper(UserMapper.class);</div><div class="line">    </div><div class="line">    <span class="comment">// 第一次查询ID为1的用户，去缓存找，找不到就去查找数据库</span></div><div class="line">    User user1 = mapper1.findUserById(<span class="number">1</span>);</div><div class="line">    System.out.println(user1);</div><div class="line">    <span class="comment">// 关闭session1</span></div><div class="line">    session1.close();</div><div class="line"></div><div class="line">    <span class="comment">// 第二次查询ID为1的用户，去缓存找，找不到就去查找数据库</span></div><div class="line">    User user2 = mapper2.findUserById(<span class="number">1</span>);</div><div class="line">    System.out.println(user2);</div><div class="line">    session2.close();</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: SELECT * FROM user WHERE id = ?; </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: 1(Integer)</span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==      Total: 1</span></div><div class="line"><span class="comment">User [id=1, username=王五, sex=2, birthday=Thu Jul 10 00:00:00 CST 2014, address=null, orders=null]</span></div><div class="line"><span class="comment">DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - Returned connection 738433734 to pool.</span></div><div class="line"><span class="comment">DEBUG [main] - Cache Hit Ratio [cn.sqdyy.mybatis.mapper.UserMapper]: 0.5</span></div><div class="line"><span class="comment">User [id=1, username=王五, sex=2, birthday=Thu Jul 10 00:00:00 CST 2014, address=null, orders=null]</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">Cache Hit Ratio：缓存命中率</span></div><div class="line"><span class="comment">第一次缓存中没有记录，则命中率0.0；</span></div><div class="line"><span class="comment">第二次缓存中有记录，则命中率0.5（访问两次，有一次命中）</span></div><div class="line"><span class="comment">*/</span></div><div class="line"></div><div class="line"><span class="comment">// 测试2：</span></div><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testTwoLevelCache2</span><span class="params">()</span> </span>&#123;</div><div class="line">    SqlSession session1 = sqlSessionFactory.openSession();</div><div class="line">    SqlSession session2 = sqlSessionFactory.openSession();</div><div class="line">    SqlSession session3 = sqlSessionFactory.openSession();</div><div class="line">    </div><div class="line">    UserMapper mapper1 = session1.getMapper(UserMapper.class);</div><div class="line">    UserMapper mapper2 = session2.getMapper(UserMapper.class);</div><div class="line">    UserMapper mapper3 = session3.getMapper(UserMapper.class);</div><div class="line">    </div><div class="line">    <span class="comment">// 第一次查询ID为1的用户，去缓存找，找不到就去查找数据库</span></div><div class="line">    User user1 = mapper1.findUserById(<span class="number">1</span>);</div><div class="line">    System.out.println(user1);</div><div class="line">    <span class="comment">// 关闭session1</span></div><div class="line">    session1.close();</div><div class="line"></div><div class="line">    <span class="comment">// 修改查询出来的结果，作为插入语句的参数</span></div><div class="line">    user1.setUsername(<span class="string">"迷"</span>);</div><div class="line">    user1.setAddress(<span class="string">"我从哪里来？"</span>);</div><div class="line">    </div><div class="line">    mapper3.insertUser(user1);</div><div class="line">    session3.commit();</div><div class="line">    <span class="comment">// 关闭session3</span></div><div class="line">    session3.close();</div><div class="line">    </div><div class="line">    <span class="comment">// 第二次查询ID为1的用户</span></div><div class="line">    User user2 = mapper2.findUserById(<span class="number">1</span>);</div><div class="line">    System.out.println(user2);</div><div class="line">    session2.close();</div><div class="line">&#125;</div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: SELECT * FROM user WHERE id = ?; </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: 1(Integer)</span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==      Total: 1</span></div><div class="line"><span class="comment">User [id=1, username=王五, sex=2, birthday=Thu Jul 10 00:00:00 CST 2014, address=null, orders=null]</span></div><div class="line"><span class="comment">DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - Returned connection 738433734 to pool.</span></div><div class="line"><span class="comment">DEBUG [main] - Opening JDBC Connection</span></div><div class="line"><span class="comment">DEBUG [main] - Checked out connection 738433734 from pool.</span></div><div class="line"><span class="comment">DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: insert into user (username,birthday,sex,address) values(?,?,?,?); </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: 迷(String), 2014-07-10 00:00:00.0(Timestamp), 2(String), 我从哪里来？(String)</span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==    Updates: 1</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: select last_insert_id(); </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: </span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==      Total: 1</span></div><div class="line"><span class="comment">DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - Returned connection 738433734 to pool.</span></div><div class="line"><span class="comment">DEBUG [main] - Cache Hit Ratio [cn.sqdyy.mybatis.mapper.UserMapper]: 0.0</span></div><div class="line"><span class="comment">DEBUG [main] - Opening JDBC Connection</span></div><div class="line"><span class="comment">DEBUG [main] - Checked out connection 738433734 from pool.</span></div><div class="line"><span class="comment">DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@2c039ac6]</span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt;  Preparing: SELECT * FROM user WHERE id = ?; </span></div><div class="line"><span class="comment">DEBUG [main] - ==&gt; Parameters: 1(Integer)</span></div><div class="line"><span class="comment">DEBUG [main] - &lt;==      Total: 1</span></div><div class="line"><span class="comment">User [id=1, username=王五, sex=2, birthday=Thu Jul 10 00:00:00 CST 2014, address=null, orders=null]</span></div><div class="line"><span class="comment">*/</span></div></pre></td></tr></table></figure></p>
<h3 id="禁用-刷新-二级缓存"><a href="#禁用-刷新-二级缓存" class="headerlink" title="禁用/刷新 二级缓存"></a>禁用/刷新 二级缓存</h3><p>如下代码所示，该statement中设置userCache=false，可以禁用当前select语句的二级缓存，即每次查询都是去数据库中查询，默认情况下是true。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findUserById"</span> <span class="attr">parameterType</span>=<span class="string">"int"</span> <span class="attr">resultType</span>=<span class="string">"cn.sqdyy.mybatis.po.User"</span> <span class="attr">useCache</span>=<span class="string">"true"</span>&gt;</span></div><div class="line">    SELECT * FROM user WHERE id = #&#123;id&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>如下代码所示，该statement中设置flushCache=true可以刷新当前的而计划从，默认情况下如果是select语句，那么flushCache是false，如果是insert，update，delete语句，那么flushCache时true。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 如果查询语句设置成true，那么每次查询都是去数据库查询，即意味着该查询的二级缓存失效。 --&gt;</span></div><div class="line"><span class="comment">&lt;!-- 如果查询语句设置成false，即使用二级缓存，那么如果在数据库中修改了数据，而缓存数据还是原来的，这个时候就会出现脏读。 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findUserById"</span> <span class="attr">parameterType</span>=<span class="string">"int"</span> <span class="attr">resultType</span>=<span class="string">"cn.sqdyy.mybatis.po.User"</span> <span class="attr">useCache</span>=<span class="string">"true"</span> <span class="attr">flushCache</span>=<span class="string">"true"</span>&gt;</span></div><div class="line">    SELECT * FROM user WHERE id = #&#123;id&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure></p>
<h3 id="MyBatis二级缓存的划分"><a href="#MyBatis二级缓存的划分" class="headerlink" title="MyBatis二级缓存的划分"></a>MyBatis二级缓存的划分</h3><p>MyBatis并不是简单地对整个Application就只有一个Cache缓存对象，它将缓存划分的更细，即是Mapper级别的，即每一个Mapper都可以拥有一个Cache对象，具体如下：</p>
<p>1、<strong>每一个Mapper分配一个Cache缓存对象</strong>(使用cache节点配置)<br><img src="http://om6odecqr.bkt.clouddn.com/%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98cache1" alt="cache"></p>
<p>2、<strong>多个Mapper共用一个Cache缓存对象</strong>(使用cache-ref节点配置)<br><img src="http://om6odecqr.bkt.clouddn.com/%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98cache2" alt="cache-ref"></p>
<h3 id="一级缓存和二级缓存的使用顺序"><a href="#一级缓存和二级缓存的使用顺序" class="headerlink" title="一级缓存和二级缓存的使用顺序"></a>一级缓存和二级缓存的使用顺序</h3><p>如果你的MyBatis使用了二级缓存，并且你的Mapper和select语句也配置使用了二级缓存，那么在执行select查询的时候，MyBatis会先从二级缓存中取输入，其次才是一级缓存，即MyBatis查询数据的顺序是：</p>
<ul>
<li>1 二级缓存</li>
<li>2 一级缓存</li>
<li>3 数据库</li>
</ul>
<h3 id="整合第三方二级缓存-Ehcache"><a href="#整合第三方二级缓存-Ehcache" class="headerlink" title="整合第三方二级缓存(Ehcache)"></a>整合第三方二级缓存(Ehcache)</h3><p>前面提到，Mybatis提供了一个cache接口，同时它有一个默认的实现类PerpetualCache。我们可以通过实现cache接口完成mybatis缓存数据通过其他缓存数据库整合，mybatis的特长是sql，缓存数据管理不是mybatis的特长，为了提高mybatis的性能，所以需要mybatis和第三方缓存数据库整合，比如ehcache、memcache、redis等。</p>
<p>Ehcache是一个分布式缓存，如果系统为了提高性能，通常会对系统采用分布式部署（集群部署方式），不使用分布式缓存，缓存的数据在各个服务单独存储，不方便开发。所以要使用分布式缓存对缓存数据进行集中式管理：<br><img src="http://om6odecqr.bkt.clouddn.com/%E5%88%86%E5%B8%83%E5%BC%8F%E7%BC%93%E5%AD%98.png" alt="分布式部署"></p>
<h4 id="整合思路"><a href="#整合思路" class="headerlink" title="整合思路"></a>整合思路</h4><p><strong>引入ehcache的jar包</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">ehcache-core.jar</div><div class="line">mybatis-ehcache.jar</div></pre></td></tr></table></figure></p>
<p><strong>配置cache的type属性</strong><br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 使用默认二级缓存 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">cache</span> <span class="attr">type</span>=<span class="string">"org.mybatis.caches.ehcache.EhcacheCache"</span> /&gt;</span></div></pre></td></tr></table></figure></p>
<p><strong>添加ehcache的配置文件</strong><br><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">ehcache</span> <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></div><div class="line"><span class="tag">	<span class="attr">xsi:noNamespaceSchemaLocation</span>=<span class="string">"../config/ehcache.xsd"</span>&gt;</span></div><div class="line">	<span class="comment">&lt;!-- 缓存数据要存放的磁盘地址 --&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">diskStore</span> <span class="attr">path</span>=<span class="string">"F:\develop\ehcache"</span> /&gt;</span></div><div class="line">	<span class="comment">&lt;!-- diskStore：指定数据在磁盘中的存储位置。</span></div><div class="line"><span class="comment">        defaultCache：当借助CacheManager.add("demoCache")创建Cache时，EhCache便会采用&lt;defalutCache/&gt;指定的的管理策略</span></div><div class="line"><span class="comment"></span></div><div class="line"><span class="comment">		以下属性是必须的：</span></div><div class="line"><span class="comment">            maxElementsInMemory - 在内存中缓存的element的最大数目</span></div><div class="line"><span class="comment">            maxElementsOnDisk - 在磁盘上缓存的element的最大数目，若是0表示无穷大</span></div><div class="line"><span class="comment">            eternal - 设定缓存的elements是否永远不过期。如果为true，则缓存的数据始终有效，如果为false那么还要根据timeToIdleSeconds，timeToLiveSeconds判断 </span></div><div class="line"><span class="comment">            overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上 </span></div><div class="line"><span class="comment">        以下属性是可选的：</span></div><div class="line"><span class="comment">            timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时，这些数据便会删除，默认值是0,也就是可闲置时间无穷大 </span></div><div class="line"><span class="comment">		    timeToLiveSeconds - 缓存element的有效生命期，默认是0.,也就是element存活时间无穷大 diskSpoolBufferSizeMB - 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区. </span></div><div class="line"><span class="comment">            diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据，默认是false。</span></div><div class="line"><span class="comment">            diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔，默认是120秒。每个120s，相应的线程会进行一次EhCache中数据的清理工作 </span></div><div class="line"><span class="comment">            memoryStoreEvictionPolicy  - 当内存缓存达到最大，有新的element加入的时候， 移除缓存中element的策略。默认是LRU（最近最少使用），可选的有LFU（最不常使用）和FIFO（先进先出） --&gt;</span></div><div class="line"></div><div class="line">	<span class="tag">&lt;<span class="name">defaultCache</span> <span class="attr">maxElementsInMemory</span>=<span class="string">"1000"</span></span></div><div class="line"><span class="tag">		<span class="attr">maxElementsOnDisk</span>=<span class="string">"10000000"</span> <span class="attr">eternal</span>=<span class="string">"false"</span> <span class="attr">overflowToDisk</span>=<span class="string">"false"</span></span></div><div class="line"><span class="tag">		<span class="attr">timeToIdleSeconds</span>=<span class="string">"120"</span> <span class="attr">timeToLiveSeconds</span>=<span class="string">"120"</span></span></div><div class="line"><span class="tag">		<span class="attr">diskExpiryThreadIntervalSeconds</span>=<span class="string">"120"</span> <span class="attr">memoryStoreEvictionPolicy</span>=<span class="string">"LRU"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">defaultCache</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">ehcache</span>&gt;</span></div></pre></td></tr></table></figure></p>
<h4 id="应用场景和局限性"><a href="#应用场景和局限性" class="headerlink" title="应用场景和局限性"></a>应用场景和局限性</h4><p>使用场景：<strong>对于访问响应速度要求高，但是实时性不高的查询，可以采用二级缓存技术。</strong></p>
<p>注意：在使用二级缓存的时候，要设置一下刷新间隔（cache标签中有一个flashInterval属性）来定时刷新二级缓存，这个刷新间隔根据具体需求来设置，比如设置30分钟、60分钟等，单位为毫秒。</p>
<p>局限性：<strong>Mybatis二级缓存对细粒度的数据级别的缓存实现不好。</strong></p>
<p>场景：对商品信息进行缓存，由于商品信息查询访问量大，但是要求用户每次查询都是最新的商品信息，此时如果使用二级缓存，就无法实现当一个商品发生变化只刷新该商品的缓存信息而不刷新其他商品缓存信息，因为二级缓存是mapper级别的，当一个商品的信息发送更新，所有的商品信息缓存数据都会清空。</p>
<p>解决此类问题，需要在业务层根据需要对数据有针对性的缓存。</p>
<p>比如可以对经常变化的 数据操作单独放到另一个namespace的mapper中。</p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-12-05T10:18:11.284Z" itemprop="dateUpdated">2017年12月5日 18:18</time>
</span><br>


        如要转载请注明出处：<a href="/2017/08/15/Mybatis_primary_07/" target="_blank" rel="external">http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/</a>
    </div>
    <footer>
        <a href="http://magic_duck.oschina.io">
            <img src="/img/avatar.jpg" alt="神奇的鸭鸭">
            神奇的鸭鸭
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/SSM/">SSM</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/&title=《Mybatis快速入门七(二级缓存)》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/&title=《Mybatis快速入门七(二级缓存)》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Mybatis快速入门七(二级缓存)》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/08/15/Mybatis_primary_08/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">Mybatis快速入门八(整合spring)</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/08/15/Mybatis_primary_06/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Mybatis快速入门六(一级缓存)</h4>
      </a>
    </div>
  
</nav>



    







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/z77z" target="_blank">邹海清</a></span>
            <span>神奇的鸭鸭の码农库 &copy; 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/&title=《Mybatis快速入门七(二级缓存)》 — 神奇的鸭鸭の码农库&pic=http://magic_duck.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/&title=《Mybatis快速入门七(二级缓存)》 — 神奇的鸭鸭の码农库&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Mybatis快速入门七(二级缓存)》 — 神奇的鸭鸭の码农库&url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/&via=http://magic_duck.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://magic_duck.oschina.io/2017/08/15/Mybatis_primary_07/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
